package cn.stylefeng.guns.modular.hp.controller;

import cn.stylefeng.guns.config.properties.GunsProperties;
import cn.stylefeng.guns.config.properties.HpProperties;
import cn.stylefeng.guns.core.common.exception.BizExceptionEnum;
import cn.stylefeng.guns.modular.hp.utils.ImgUploadJsonResult;
import cn.stylefeng.guns.modular.hp.utils.ImgUploadJsonResultUtil;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
 * 图片上传控制器
 *
 * @author xzqiang
 * @date 2018-12-12
 */
@Controller
@RequestMapping("/hp/pic")
public class PicController extends BaseController {

	@Autowired
    private GunsProperties gunsProperties;
	
	@Autowired
    private HpProperties hpProperties;
	
	 /**
     * 上传图片
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile picture) {

        String pictureName = UUID.randomUUID().toString() + "." + ToolUtil.getFileSuffix(picture.getOriginalFilename());
        try {
            String fileSavePath = gunsProperties.getFileUploadPath();
            picture.transferTo(new File(fileSavePath + pictureName));
        } catch (Exception e) {
            throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return hpProperties.getStaticPicUrl() + pictureName;
    }
    
    /**
     * 上传图片
     */
    @RequestMapping(method = RequestMethod.POST, path = "/wangeditorUpload")
    @ResponseBody
    public ImgUploadJsonResult wangeditorUpload(MultipartFile picture, HttpServletRequest request) {

        String pictureName = UUID.randomUUID().toString() + "." + ToolUtil.getFileSuffix(picture.getOriginalFilename());
        //{request.getContextPath() + "/upload/" + realName};
        String [] pics = new String[1];
        //List<String> picList = new ArrayList<String>();
        try {
            String fileSavePath = gunsProperties.getFileUploadPath();
            picture.transferTo(new File(fileSavePath + pictureName));
            pics[0] = hpProperties.getStaticPicUrl() + pictureName;
        } catch (Exception e) {
            throw new ServiceException(BizExceptionEnum.UPLOAD_ERROR);
        }
        
        return ImgUploadJsonResultUtil.success(pics);
    }

}
